/*
 * 找出当前目录下的时间戳最小文件  ls -t | sort | sed -n 1p
 * 获取当前磁盘的剩余空间    df  ../clean_old_file | awk  '{print $4}' | sed -n
 * 2p
 */

#include <dirent.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/vfs.h>
#include <unistd.h>

// 获取当前当前用户可操作的磁盘空余容量
int getDiskAvailableSize(char *folderPath) {
  struct statfs diskInfo;
  if (statfs(folderPath, &diskInfo) == -1) {
    return -1;
  }
  unsigned long long availableDisk = diskInfo.f_bavail * diskInfo.f_bsize;
  // std::cout << "磁盘可用空间" << (availableDisk >> 20) << std::endl;
  return availableDisk;
}

// 删除目录下创建时间最早的文件夹
int delMinTimeFile(char *folderPath) {
  DIR *pDir = NULL;
  struct dirent *pDirent = NULL;

  pDir = opendir(folderPath);
  if (pDir == NULL) {
    return -1;
  }

  int ret;
  char *fileName = (char *)malloc(256);
  memset(fileName, 0, 256);
  char *firstTimefileName = (char *)malloc(256);
  struct stat *filetime = (struct stat *)malloc(sizeof(struct stat));
  long int preTime = pow(2, sizeof(long int) * 8 - 16);
  while ((pDirent = readdir(pDir)) != NULL) {
    if (pDirent->d_name[0] == '.' && pDirent->d_name[1] == 0 ||
        pDirent->d_name[0] == '.' && pDirent->d_name[1] == '.' &&
            pDirent->d_name[2] == 0) {
      continue;
    }
    sprintf(
        fileName, "%s%s%s", folderPath, "/",
        pDirent
            ->d_name);  // baichao,todo,此处添加一下对于路径是不是以'/'结尾逻辑会更健全。
    memset(filetime, 0, sizeof(struct stat));
    ret = stat(fileName, filetime);
    if (-1 == ret) {
      return -1;
    }

    printf("1:%s\n", fileName);
    long int _time = (int)filetime->st_mtime;  // 获取文件的创建时间
    if (_time < preTime) {
      memset(firstTimefileName, 0, 256);
      sprintf(firstTimefileName, "%s", fileName);
      preTime = _time;
    }
  }

  printf("2:%s\n", firstTimefileName);
  remove(firstTimefileName);
  closedir(pDir);
}

int main() {
  char folderPath[] = "./log";
  getDiskAvailableSize(folderPath);

  delMinTimeFile(folderPath);
  return 0;
}
